﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Security.Policy;
using static System.Windows.Forms.AxHost;
using System.Runtime.Serialization.Json;

namespace JiaBoPrint
{
    class Helper
    {
        //DateTime类型转换为时间戳(毫秒值)
        public static long DateToTicks(DateTime? time)
        {
            //return ((time.HasValue ? time.Value.Ticks : DateTime.Now.ToUniversalTime().Ticks) - 621355968000000000) / 10000;
            //return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return (time.Value.Ticks - 621355968000000000) / 10000;
           
        }
    
        public static long DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (long)(time - startTime).TotalMilliseconds;
        }
        public static long DateToTicks2(DateTime? time)
        {
            return ((time.HasValue ? time.Value.Ticks : DateTime.Parse("1990-01-01").ToUniversalTime().Ticks) - 621355968000000000) / 10000;
            //return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        }

        //时间戳(毫秒值)String转换为DateTime类型转换
        public static DateTime TicksToDate(string time)
        {
            return new DateTime((Convert.ToInt64(time) * 10000) + 621355968000000000);
        }
        public static async Task<retMessage> post_PosData(string url, string token, string postBody)
        {
            retMessage ret = new retMessage();

            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(url);
            //表头参数
            string version = "v1";
            token = "bearer" + token;
            httpClient.DefaultRequestHeaders.Add("api-version", version);
            httpClient.DefaultRequestHeaders.Add("Authorization", token);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                using (var request = new HttpRequestMessage())
                {
                    //var postBody = $"{{\"identity\":\"{body}\",\"phoneNumber\":\"{phoneNumber}\",\"code\":\"[code]\"}}";
                    request.Method = HttpMethod.Post;
                    request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
                    var response = await httpClient.SendAsync(request);
                    //返回结果
                    var retString = await response.Content.ReadAsStringAsync();
                    string retCode = "";
                    string retMessage = "";
                    if (retString == "true")
                    {
                        retCode = "200";
                        retMessage = "成功";
                    }
                    else
                    {
                        JObject items = (JObject)JsonConvert.DeserializeObject(retString);
                        string errorDescription = items["errorDescription"].ToString();
                        retCode = "300";
                        retMessage = errorDescription;
                    }
                    ret.retCode = retCode;
                    ret.message = retMessage;
                }
            }
            catch (Exception e)
            {
                ret.retCode = "300";
                ret.message = e.Message.ToString();
            }
            return ret;
        }


        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="Url">地址</param>
        /// <param name="postDataStr">参数：格式"roleId=1&uid=2"</param>
        /// <returns></returns>
        public static string HttpGet_query(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="Url">地址</param>
        /// <param name="postDataStr">参数：格式"roleId=1&uid=2"</param>
        /// <returns></returns>
        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        public static async Task<retMessage> get_tokenAsync(string url, string postBody)
        {
            retMessage ret = new retMessage();

            //string url = "https://cloud.soei.com.cn/smsapi/sms/verifycode";
            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(url);
            //表头参数
            string version = "v1";
            httpClient.DefaultRequestHeaders.Add("api-version", version);
            //string token = "9c0025b4aae442bda5498971ec1ab219";
            //httpClient.DefaultRequestHeaders.Add("token", token);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                using (var request = new HttpRequestMessage())
                {
                    //var postBody = $"{{\"identity\":\"{body}\",\"phoneNumber\":\"{phoneNumber}\",\"code\":\"[code]\"}}";
                    request.Method = HttpMethod.Post;
                    request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
                    var response = await httpClient.SendAsync(request);
                    //返回结果
                    var retString = await response.Content.ReadAsStringAsync();
                    JObject items = (JObject)JsonConvert.DeserializeObject(retString);
                    //返回码，成功为200
                    string accessToken = items["accessToken"].ToString();
                    //返回消息
                    string retCode = "200";
                    if (accessToken == "" || accessToken == null)
                    {
                        retCode = "300";
                    }
                    ret.retCode = retCode;
                    ret.message = accessToken;


                    ////返回码，成功为200
                    //string retCode = items["code"].ToString();
                    ////返回消息
                    //string message = items["message"].ToString();
                    //string data = items["data"].ToString();
                    //JObject items_data = (JObject)JsonConvert.DeserializeObject(data);
                    //string isSuccess = items_data["isSuccess"].ToString();
                    //string data_message = items_data["message"].ToString();
                    //if (isSuccess == "False")
                    //{
                    //    retCode = "300";
                    //}
                    //ret.retCode = retCode;
                    //ret.message = data_message;
                }
            }
            catch (Exception e)
            {
                ret.retCode = "300";
                ret.message = e.Message.ToString();
            }

            return ret;
        }

        /// <summary>  
        /// 获取Json的Model  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="szJson"></param>  
        /// <returns></returns>  
        public static T JsonToEntity<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
        /// <summary>
        /// 统一接口Json返回结果格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class retMessage<T> where T : class
        {
            /// <summary>
            /// 状态码
            /// </summary>
            public string retCode { get; set; }

            /// <summary>
            /// 附加消息
            /// </summary>
            public string message { get; set; }

            /// <summary>
            /// 附加数据
            /// </summary>
            public T Result { get; set; }
        }

        public static string postrequest(string url, string body)
        {
            //定义request并设置request的路径
            WebRequest request = WebRequest.Create(url);
            request.Method = "post";

            //设置参数的编码格式，解决中文乱码
            byte[] byteArray = Encoding.UTF8.GetBytes(body);

            //设置request的MIME类型及内容长度
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            //打开request字符流
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            //定义response为前面的request响应
            WebResponse response = request.GetResponse();
            //获取相应的状态代码
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            //定义response字符流
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();//读取所有
            return responseFromServer;
        }
        public static string Trim(Object temp)
        {
            try
            {
                string t = temp.ToString().Trim();
                return t;
            }
            catch (Exception e)
            {
                return "";
            }

        }
    }
}
